package repository

import "gorm.io/gorm"

type IdNums []IdNum

type IdNum struct {
	Id     int    `json:"-" gorm:"column:id;primary_key;AUTO_INCREMENT"` // 主键id
	Name   string `json:"name" gorm:"column:name"`                       //姓名
	IdNum  string `json:"idNum" gorm:"column:id_num"`                    // 身份证号
	Source int    `json:"-" gorm:"column:source"`                        // 来源
	UsedBy UserId `json:"-" gorm:"column:used_by"`                       // 被谁用（用户id）
}

func (i *IdNum) TableName() string {
	return "id_num"
}

func IdNumModel() *gorm.DB {
	return DB.Model(&IdNum{})
}

func GetUserIdNum(userId UserId, source int) (res IdNums, err error) {
	err = IdNumModel().Where(IdNum{UsedBy: userId, Source: source}).Find(&res).Order("id ASC").Error
	return
}

func (ui UserId) GetIdNumsByCount(count int) (IdNums, error) {
	tx := DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 获取count条UsedBy为空的IdNum记录
	var idNums *IdNums
	if err := tx.Where("used_by is null").Limit(count).Find(&idNums).Order("id ASC").Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	// 更新UsedBy为userId
	for _, idNum := range *idNums {
		if err := tx.Model(idNum).Update("used_by", ui).Error; err != nil {
			tx.Rollback()
			return nil, err
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return nil, err
	}
	return *idNums, nil
}
